<template>
  <div class="app-container">
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="商家名称/联系电话"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.business_type_id" placeholder="商家类型" clearable>
            <el-option
              v-for="item in options.business_types"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option
              v-for="(label, value) in options.status"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增商家</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="name" label="商家名称" min-width="150" />
        <el-table-column prop="business_type_name" label="商家类型" width="100" />
        <el-table-column prop="contact_phone" label="联系电话" width="120" />
        <el-table-column prop="service_level_text" label="服务等级" width="100" />
        <el-table-column prop="address" label="详细地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button
              :type="row.status ? 'danger' : 'success'"
              link
              @click="handleStatus(row)"
            >
              {{ row.status ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增商家' : '编辑商家'"
      v-model="dialogVisible"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商家名称" />
        </el-form-item>
        <el-form-item label="商家类型" prop="business_type_id">
          <el-select v-model="form.business_type_id" placeholder="请选择商家类型">
            <el-option
              v-for="item in options.business_types"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="form.contact_phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="服务等级" prop="service_level">
          <el-select v-model="form.service_level" placeholder="请选择服务等级">
            <el-option
              v-for="(label, value) in options.service_levels"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预充值额度" prop="deposit_amount">
          <el-input-number
            v-model="form.deposit_amount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="景区描述" prop="area_desc">
          <rich-text-editor v-model="form.area_desc" />
        </el-form-item>
        <el-form-item label="服务项目" prop="service_items">
          <rich-text-editor v-model="form.service_items" />
        </el-form-item>
        <el-form-item label="服务内容" prop="service_content">
          <rich-text-editor v-model="form.service_content" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog
      title="商家详情"
      v-model="detailVisible"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="商家类型">{{ detail.business_type_name }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detail.contact_phone }}</el-descriptions-item>
        <el-descriptions-item label="服务等级">{{ detail.service_level_text }}</el-descriptions-item>
        <el-descriptions-item label="详细地址" :span="2">{{ detail.address }}</el-descriptions-item>
        <el-descriptions-item label="预充值额度">{{ detail.deposit_amount }}元</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detail.status ? 'success' : 'danger'">
            {{ detail.status_text }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.created_at }}</el-descriptions-item>
        <el-descriptions-item label="景区描述" :span="2">
          <div v-html="detail.area_desc || '-'" />
        </el-descriptions-item>
        <el-descriptions-item label="服务项目" :span="2">
          <div v-html="detail.service_items || '-'" />
        </el-descriptions-item>
        <el-descriptions-item label="服务内容" :span="2">
          <div v-html="detail.service_content || '-'" />
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import RichTextEditor from '@/components/RichTextEditor.vue'

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  keyword: '',
  business_type_id: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 选项数据
const options = reactive({
  business_types: {},
  service_levels: {},
  status: {}
})

// 获取选项数据
const getOptions = async () => {
  try {
    const res = await request.get('/business-partner/all')
    options.business_types = res.data.business_types
    options.service_levels = res.data.service_levels
    options.status = res.data.status
  } catch (error) {
    console.error('获取选项数据失败：', error)
  }
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/business-partner/list', {
      params: queryParams
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.keyword = ''
  queryParams.business_type_id = ''
  queryParams.status = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

// 表单数据
const form = reactive({
  partner_id: undefined,
  name: '',
  business_type_id: '',
  contact_phone: '',
  address: '',
  service_level: 'normal',
  area_desc: '',
  service_items: '',
  service_content: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商家名称', trigger: 'blur' }
  ],
  business_type_id: [
    { required: true, message: '请选择商家类型', trigger: 'change' }
  ],
  contact_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ],
  service_level: [
    { required: true, message: '请选择服务等级', trigger: 'change' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    partner_id: undefined,
    name: '',
    business_type_id: '',
    contact_phone: '',
    address: '',
    service_level: 'normal',
    area_desc: '',
    service_items: '',
    service_content: '',
    status: 1
  })
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    partner_id: row.partner_id,
    name: row.name,
    business_type_id: row.business_type_id,
    contact_phone: row.contact_phone,
    address: row.address,
    service_level: row.service_level,
    area_desc: row.area_desc,
    service_items: row.service_items,
    service_content: row.service_content,
    status: row.status
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate()
  
  try {
    const url = dialogType.value === 'add' ? '/business-partner/add' : '/business-partner/edit'
    const res = await request.post(url, form)
    if (res.code === 0) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      getList()
    }
  } catch (error) {
    console.error(dialogType.value === 'add' ? '添加失败' : '更新失败', error)
  }
}

// 详情
const detailVisible = ref(false)
const detail = ref({})

const handleDetail = async (row) => {
  try {
    const { data } = await request.get('/business-partner/detail', {
      params: {
        partner_id: row.partner_id
      }
    })
    detail.value = data
    detailVisible.value = true
  } catch (error) {
    console.error(error)
  }
}

// 更改状态
const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认要${row.status ? '停用' : '启用'}该商家吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await request.post('/business-partner/status', {
      partner_id: row.partner_id,
      status: row.status ? 0 : 1
    })
    
    if (res.code === 0) {
      ElMessage.success('状态更新成功')
      getList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新状态失败：', error)
    }
  }
}

// 初始化
onMounted(() => {
  getOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.ml-2 {
  margin-left: 8px;
}

:deep(.w-e-text-container) {
  min-height: 200px !important;
}

:deep(.el-descriptions-item__content) {
  word-break: break-word;
}

:deep(.el-descriptions-item__content img) {
  max-width: 100%;
  height: auto;
}
</style> 